package com.guanjialhx.utils;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author LiXiang
 * @version V1.0.1
 * 注意 本内容仅限于长护宝科技有限公司，禁止外泄以及用于其他的商业
 * @projectName WeChatUtil
 * @package com.wechatchb.chb.utils
 * @description
 * @DATE: 2021/3/29
 * @TIME: 10:52 上午
 * @YEAR: 2021
 * <p>
 * 微信公众号
 */
public class WeChatUtil {
    public static final Logger log = LoggerFactory.getLogger(WeChatUtil.class);
    /**
     * 向用户发送信息
     *
     * @param serverURL
     * @param jsonObject
     * @return
     */
    public static String sendInformationToUsers(String serverURL, JSONObject jsonObject) {
        try {
            StringBuffer sbf = new StringBuffer();
            String strRead = null;
            URL url = new URL(serverURL);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            //header内的的参数在这里set    connection.setRequestProperty("健, "值");
            connection.setRequestProperty("Content-Type", "application/json; encoding=utf-8");

            connection.connect();
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            writer.write(jsonObject.toString());
            writer.flush();
            InputStream is = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            connection.disconnect();
            String results = sbf.toString();
            log.info("公众号通知发送结果sendInformationToUsers_results="+results);
            return results;
        } catch (Exception e) {
            e.printStackTrace();
//            return e.printStackTrace();
            return "发送失败";
        }

    }

    /**
     * 获取微信Access_token
     *
     * @return
     */
    public static String getAccess_token(String appId,String appSecret) {
        try {
//            String appId = "wxfb08c471b5a5b1cc";
//            String appSecret = "ceb8259f4335e59bfecac3edde974cf7";
            // 获取公众号号调用凭证access_token
            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            String access_tokenJson = httpGetJson(url);
            log.info("access_tokenJson="+access_tokenJson);
            // String类型转Json对象并获取指定数据
            JsonObject jsonObject = new JsonParser().parse(access_tokenJson).getAsJsonObject();
            //通过getAsJsonArray获取：对应的[]里面的数据
            String access_token = jsonObject.getAsJsonObject().get("access_token").getAsString();
            return access_token;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("getAccess_token="+e);
            return null;
        }

    }

    public static String httpGetJson(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            //connection.setRequestProperty("contentType", "utf8");
            connection.setReadTimeout(5000);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            // Map<String, List<String>> map = connection.getHeaderFields();


            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), "UTF-8"));//防止乱码
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = "";
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

        return result;
    }
}
